package com.mercator.client.graph;

import java.util.Arrays;
import java.util.LinkedList;

import org.vaadin.gwtgraphics.client.DrawingArea;
import org.vaadin.gwtgraphics.client.Line;
import org.vaadin.gwtgraphics.client.Shape;
import org.vaadin.gwtgraphics.client.shape.Circle;

public class DGeneSetMap extends DGraph<GenType,GenStringNode<? extends Shape>, GeneSetMap<GenStringNode<? extends Shape>,GenNode,GenSetNode>> {

	private Factory geneFactory;
	public static final MapName NAME =  MapName.GENESET_MAP;
	public DGeneSetMap(DrawingArea canvas) {
		super(canvas);
		this.factory = geneFactory = new Factory();
		this.container = new GeneSetMap<GenStringNode<? extends Shape>,GenNode, GenSetNode>();
	}
	
	public  void  animate() {
		int cols,rows,deg_threshold,max_inrow, max_deg, padding, width, height,genset_col;
		String[] colors = {"red","blue","green","yellow","orange"};
		cols = max_deg = 4;
		int[] r_arr = new int[cols];
		Arrays.fill(r_arr, 1);
		rows = max_inrow = 30;
		int cur_col =1;
		genset_col = 3;
		deg_threshold = 0;
		padding =200;
		width = canvas.getWidth() - padding;
		height = canvas.getHeight() - padding;
		//naive implementation
		int row=1 ,col = 1;	
		for (GenStringNode<? extends Shape> v : container.getGeneSets())
		{
				v.animate();
				v.moveTo(width/(cols)*genset_col, height/(rows)*row+row*v.radius*2);
				row++;		
		}
		cur_col = row = col = 1;	
		
		System.out.println(container.getGenes());
		for(GenStringNode<? extends Shape> u: container.getGenes())
		{	
			col = cur_col; cur_col = u.getDegree();
			cur_col = (cur_col == genset_col)? cur_col + 1: cur_col;
			row = r_arr[cur_col-1];
			LinkedList<Line> ll = new LinkedList<Line>();
			ll.addAll(u.outedges.values());
			ll.addAll(u.inedges.values());
			for (Line l : ll)
				l.setStrokeColor(colors[cur_col]);
			u.animate();
			u.moveTo(width/(cols)*cur_col, height/(rows)*row+row*u.radius);
			r_arr[cur_col-1]++;
		}
				
	}

	@Override
	public void move() {
		this.animate();
	}
	
	

	@Override
	public void moveTo(double x, double y) {
		// TODO Auto-generated method stub
		
	}
	
	public class Factory extends NodeFactory<GenType,GenStringNode<? extends Shape>> {
		public GenStringNode<? extends Shape> create(GenType t) {
			if(!container.hasVertex(t))
				if(t.type == GenType.Type.GENE)
					return create((Gene)t);
				else return create((GeneSet)t);
			return container.find(t);
		}
		
		public GenNode create(Gene g){
			return  new GenNode(canvas,g);
		}
		
		public GenSetNode create(GeneSet gs){
			return new GenSetNode(canvas,gs);
		}
	}
	
	public void connect(GeneSet geneset,Gene gene){
		container.connectGenes(geneFactory.create(gene), geneFactory.create(geneset));
	}

	@Override
	public MapName getName() {
		return NAME;
	}

}
